package net.hn.hnms.biz.process.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.hn.hnms.biz.api.mine.RemoteMineInfoService;
import net.hn.hnms.biz.api.mine.model.WeChartBaseMessage;
import net.hn.hnms.biz.process.domain.*;
import net.hn.hnms.biz.process.domain.dto.*;
import net.hn.hnms.biz.process.domain.vo.ApproveVo;
import net.hn.hnms.biz.process.mapper.*;
import net.hn.hnms.biz.process.service.WorkTicketFlowService;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.core.utils.StringUtils;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import net.hn.hnms.sys.common.satoken.utils.LoginHelper;
import net.hn.hnms.sys.system.api.RemoteUserService;
import net.hn.hnms.sys.system.api.model.LoginUser;
import net.hn.hnms.sys.system.api.model.UserVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WorkTicketFlowServiceImpl implements WorkTicketFlowService {
    /**
     * 工作票
     */
    @Resource
    private WorkTicketMapper workTicketMapper;
    /**
     * 流程定义
     */
    @Resource
    private WorkTicketFlowMapper workTicketFlowMapper;
    @Resource
    private WorkTickStopsendOneMapper workTickStopsendOneMapper;
    @Resource
    private WorkTicketDataMapper workTicketDataMapper;
    @Resource
    private WorkTicketFlowDataMapper workTicketFlowDataMapper;

    /**
     * 远程调用User
     */
    @Resource
    private RemoteUserService remoteUserService;
    @Resource
    private WorkPersonMapper workPersonMapper;

    /**
     * 发送审批通知
     */
    @Resource
    private RemoteMineInfoService remoteMineInfoService;
    /**
     * 审批流程
     */
//    @Resource
//    private ProcessService processService;

    /**
     * 功能描述: 工作票设置操作或设置审批流程
     *
     * @param workTicketFlowPo
     * @return java.lang.Boolean
     * @auther: WangLong
     * @date: 2022/8/10 16:41
     */

    @Override
    public Boolean addApprove(WorkTicketFlowPo workTicketFlowPo) {
        // 获取工作票id
        String workTicketId = workTicketFlowPo.getWorkTicketId();
        WorkTicketPo workTicketPo = workTicketMapper.selectById(workTicketId);
        if (workTicketPo == null) {
            throw new HuaNengException(Constants.FAIL, "未查询到工作票" + workTicketId);
        }
        // 初始化流程状态(0未完成,1已完成)
        workTicketFlowPo.setFlowStatus("0");
        workTicketFlowMapper.selectById(workTicketFlowPo.getFlowSchemeId());
        // 获取序列号列表
        if (StringUtils.isEmpty(workTicketFlowPo.getSerialNumbers())) {
            throw new HuaNengException(Constants.FAIL, "选中的序号列表为空");
        }
//        // 判断前端是否传来发起人
//        String approverId = workTicketFlowPo.getInitiatorId();
//        if (StringUtils.isEmpty(approverId)) {
//            // 设置流程发起人
//            workTicketFlowPo.setInitiatorId(getLoginUserInfo().getLoginId());
//            workTicketFlowPo.setInitiatorName(getLoginUserInfo().getUsername());
//
//        }
        //保存该流程审批
        int insert = workTicketFlowMapper.insert(workTicketFlowPo);
        if (insert == 0) {
            throw new HuaNengException(Constants.FAIL, "审批流程保存失败");
        }

        String[] split = workTicketFlowPo.getSerialNumbers().split(",");
        WorkTickStopsendOnePo workTickStopsendOnePo = workTickStopsendOneMapper.selectOne(new LambdaQueryWrapper<WorkTickStopsendOnePo>()
                .eq(WorkTickStopsendOnePo::getWorkTicketId, workTicketId));
        if (workTickStopsendOnePo == null) {
            workTickStopsendOnePo = new WorkTickStopsendOnePo();
        }
        //添加工作票管理父id
        workTickStopsendOnePo.setWorkTicketId(workTicketFlowPo.getWorkTicketId());
        for (String s : split) {
            switch (s) {
                case "1":
                    workTickStopsendOnePo.setSerialNumber1Status("1");
                    break;
                case "2":
                    workTickStopsendOnePo.setSerialNumber2Status("1");
                    break;
                case "3":
                    workTickStopsendOnePo.setSerialNumber3Status("1");
                    break;
                case "4":
                    workTickStopsendOnePo.setSerialNumber4Status("1");
                    break;
                case "5":
                    workTickStopsendOnePo.setSerialNumber5Status("1");
                    break;
                case "6":
                    workTickStopsendOnePo.setSerialNumber6Status("1");
                    break;
                case "7":
                    workTickStopsendOnePo.setSerialNumber7Status("1");
                    break;
                case "8":
                    workTickStopsendOnePo.setSerialNumber8Status("1");
                    break;
                case "9":
                    workTickStopsendOnePo.setSerialNumber9Status("1");
                    break;
                case "10":
                    workTickStopsendOnePo.setSerialNumber10Status("1");
                    break;
                case "11":
                    workTickStopsendOnePo.setSerialNumber11Status("1");
                    break;
                case "12":
                    workTickStopsendOnePo.setSerialNumber12Status("1");
                    break;
                case "13":
                    workTickStopsendOnePo.setSerialNumber13Status("1");
                    break;
                case "14":
                    workTickStopsendOnePo.setSerialNumber14Status("1");
                    break;
                case "15":
                    workTickStopsendOnePo.setSerialNumber15Status("1");
                    break;
                case "16":
                    workTickStopsendOnePo.setSerialNumber16Status("1");
                    break;
                case "17":
                    workTickStopsendOnePo.setSerialNumber17Status("1");
                    break;
                case "18":
                    workTickStopsendOnePo.setSerialNumber18Status("1");
                    break;
                case "19":
                    workTickStopsendOnePo.setSerialNumber19Status("1");
                    break;
                case "20":
                    workTickStopsendOnePo.setSerialNumber20Status("1");
                    break;
                case "21":
                    workTickStopsendOnePo.setSerialNumber21Status("1");
                    break;
                case "22":
                    workTickStopsendOnePo.setSerialNumber22Status("1");
                    break;
                case "23":
                    workTickStopsendOnePo.setSerialNumber23Status("1");
                    break;
                case "24":
                    workTickStopsendOnePo.setSerialNumber24Status("1");
                    break;
                case "25":
                    workTickStopsendOnePo.setSerialNumber25Status("1");
                    break;
                case "26":
                    workTickStopsendOnePo.setSerialNumber26Status("1");
                    break;
                case "27":
                    workTickStopsendOnePo.setSerialNumber27Status("1");
                    break;
                case "28":
                    workTickStopsendOnePo.setSerialNumber28Status("1");
                    break;
                case "29":
                    workTickStopsendOnePo.setSerialNumber29Status("1");
                    break;
                case "30":
                    workTickStopsendOnePo.setSerialNumber30Status("1");
                    break;
                case "31":
                    workTickStopsendOnePo.setSerialNumber31Status("1");
                    break;
            }
        }
        int insert1 = workTickStopsendOneMapper.updateById(workTickStopsendOnePo);
        if (insert1 == 0) {
            throw new HuaNengException(Constants.FAIL, "停送电工作票第一种更新失败");
        }
        return true;
    }

    /**
     * 功能描述: 获取工作票审批列表
     *
     * @param pageQuery
     * @param approveDto
     * @return net.hn.hnms.sys.common.mybatis.core.page.TableDataInfo<net.hn.hnms.biz.process.domain.vo.WorkTicketFlowOneVo>
     * @auther: WangLong
     * @date: 2022/8/11 17:26
     */

    @Override
    public ResponsePage<List<ApproveVo>> approvePageList(PageQuery pageQuery, ApproveDto approveDto) {
        LambdaQueryWrapper<WorkDataPo> wrapper = new LambdaQueryWrapper<>();
        //分类ID
        wrapper.eq(StringUtils.isNotEmpty(approveDto.getTicketTypeId()), WorkDataPo::getTicketTypeId, approveDto.getTicketTypeId());
        //分类名称
        wrapper.eq(StringUtils.isNotEmpty(approveDto.getTicketName()), WorkDataPo::getTickName, approveDto.getTicketName());
        //发起日期
        wrapper.eq(approveDto.getFlowTakeDate() != null, WorkDataPo::getFlowTakeDate, approveDto.getFlowTakeDate());
        wrapper.eq(StringUtils.isNotBlank(approveDto.getMineCode()), WorkDataPo::getMineCode, approveDto.getMineCode());
        wrapper.orderByDesc(WorkDataPo::getCreateTime);
        //流程状态（0未启用，1开启）
//        wrapper.eq(WorkTicketPo::getFlowStatus, "1");
//        Page<WorkTicketPo> workTicketPoPage = workTicketMapper.selectPage(pageQuery.build(), wrapper);
        if (pageQuery.getPageNum() != null) {
            pageQuery.setPageNum(pageQuery.getPageNum() + 1);
        }
        Page<WorkDataPo> workDataPoPage = workTicketDataMapper.selectPage(pageQuery.build(), wrapper);
        if (workDataPoPage.getRecords().isEmpty()) {
            return new ResponsePage<>(new ArrayList(), 0);
        }
        List<ApproveVo> collect = workDataPoPage.getRecords().stream().map(t -> {
            //返回数据
            ApproveVo approveVo = new ApproveVo();
            //工作票ID
            approveVo.setTicketId(t.getTickDataId());
            //工作票名称
            approveVo.setTicketName(t.getTickName());
            //工作票数据名称
            approveVo.setTickDataName(t.getTickDataName());
            //工作票分类ID
            approveVo.setTicketTypeId(t.getTicketTypeId());
            //工作票分类名称
            approveVo.setTicketTypeName(t.getTicketTypeName());
            //发起人ID
            approveVo.setInitiatorId(t.getInitiatorId());
            //发起人名称
            approveVo.setInitiatorName(t.getInitiatorName());
            //发起日期
            approveVo.setFlowTakeDate(t.getFlowTakeDate());
            String flowStatus = t.getFlowStatus();
            //未完成
            if ("0".equals(flowStatus)) {
                WorkFlowDataPo workFlowDataPos = workTicketFlowDataMapper.selectOne(new LambdaQueryWrapper<WorkFlowDataPo>().eq(WorkFlowDataPo::getTicketDataId, t.getTickDataId()).eq(WorkFlowDataPo::getFlowStatus, "1"));
                //步骤状态
                approveVo.setFlowStatus(workFlowDataPos.getFlowNumber() + "/" + workTicketFlowDataMapper.selectCount(new LambdaQueryWrapper<WorkFlowDataPo>().eq(WorkFlowDataPo::getTicketDataId, t.getTickDataId())));


                //已完成
            } else if ("1".equals(flowStatus)) {
                approveVo.setFlowStatus("已完成");
                //拒绝
            } else if ("2".equals(flowStatus)) {
                approveVo.setFlowStatus("已拒绝");

            } else if ("3".equals(flowStatus)) {
                approveVo.setFlowStatus("已撤销");
            } else {
                approveVo.setFlowStatus("未知");
            }
            return approveVo;
        }).collect(Collectors.toList());
        return new ResponsePage<>(collect, workDataPoPage.getTotal());
    }

    /**
     * 功能描述: 发起审批流程
     *
     * @param workTicketFlowDto
     * @return java.lang.Boolean
     * @auther: WangLong
     * @date: 2022/8/11 17:34
     */

    @Override
    public Boolean startApprove(WorkTicketFlowDto workTicketFlowDto) {
        String workTicketId = workTicketFlowDto.getWorkTicketId();
        WorkTicketPo workTicketPo = workTicketMapper.selectById(workTicketId);
        if (workTicketPo == null) {
            throw new HuaNengException(Constants.FAIL, "未查询到工作票:" + workTicketId);
        }

        // 生成工作票数据表jilu
        WorkDataPo workDataPo = new WorkDataPo();
        //工作票ID
        workDataPo.setWorkTicketId(workTicketId);
        //工作票名称
        workDataPo.setTickDataName(workTicketFlowDto.getWorkTicketName());
        //工作票分类ID和name
        workDataPo.setTicketTypeId(workTicketPo.getTicketTypeId());
        workDataPo.setTicketTypeName(workTicketPo.getTicketTypeName());
        workDataPo.setTickName(workTicketPo.getTicketName());
        //流程发起时间
        workDataPo.setFlowTakeDate(new Date());
        //获取登录人信息
        LoginUser loginUserInfo = getLoginUserInfo();
        //发起人ID
        workDataPo.setInitiatorId(loginUserInfo.getUserId().toString());
        //发起人Name
        workDataPo.setInitiatorName(loginUserInfo.getUsername());
        //流程状态
        workDataPo.setFlowStatus("0");
        //表单数据
        workDataPo.setFromData(workTicketFlowDto.getFromData());
        workTicketDataMapper.insert(workDataPo);

        List<WorkTicketDto> procedureList = workTicketFlowDto.getProcedureList();
        //流程序号
        int count = 0;
        for (WorkTicketDto workTicketDto : procedureList) {

            //生成流程数据
            WorkFlowDataPo workFlowDataPo = new WorkFlowDataPo();
            //流程ID
            workFlowDataPo.setFlowId(workTicketDto.getFlowSchemeId());
            //职位ID
            workFlowDataPo.setPositionId(workTicketDto.getPositionId());
            //职位名称
            workFlowDataPo.setPositionName(workTicketDto.getPositionName());
            //工作流流程ID
            //流程状态(将第一个设置为审批中)
            if (count == 0) {
                workFlowDataPo.setFlowStatus("1");
                List<String> toUser = new ArrayList();
                //获取当前审批人，给审批人发送消息
                if (workTicketDto.getApproverId() != null) {
                    toUser.add(workTicketDto.getApproverId());
                    WeChartBaseMessage msg = new WeChartBaseMessage();
                    String content = "有待您审批的流程——" + "" + ",请登陆系统后审批。";
                    msg.setContent(content);
                    msg.setPassword("hn@2022");
                    msg.setToUsers(org.apache.commons.lang3.StringUtils.join(toUser, ","));
                    try {
                        remoteMineInfoService.sendBaseMessage(msg);
                    } catch (Exception e) {
                        System.out.println("发送审批消息失败，flowID，审批人" +workTicketDto.getFlowSchemeId()+","+ workTicketDto.getApproverId());
                        e.printStackTrace();
                    }

                }
            } else {
                workFlowDataPo.setFlowStatus("0");
            }
            //流程序号
            workFlowDataPo.setFlowNumber(count);
            //流程序号++（+1）后面需要列表排序
            count++;
            //审批人ID
            workFlowDataPo.setApproverId(workTicketDto.getApproverId());
            //审批人名称
            workFlowDataPo.setApproverName(workTicketDto.getApproverName());
            //工作票数据ID
            workFlowDataPo.setTicketDataId(workDataPo.getTickDataId());
            //选中的序号列表
            workFlowDataPo.setSerialNumbers(workTicketDto.getSerialNumbers());
            //流程父ID
            workFlowDataPo.setFlowId(workTicketDto.getFlowSchemeId());
            //表单数据
            workFlowDataPo.setJsonFrom(workTicketDto.getJsonFrom());

            workTicketFlowDataMapper.insert(workFlowDataPo);

        }
        //processName  使用工作票名字+工作票ID

        // 使用Activiti开启工作流
        //禁用activiti
//        this.startProcess(workDataPo.getTickDataId(),
//                workDataPo.getTickName() + workDataPo.getWorkTicketId(),
//                loginUserInfo.getUserId() + "," + loginUserInfo.getUsername());

        return true;
    }

    /**
     * 创建流程定义
     *
     * @param workTicketFlowDto
     * @param loginUserInfo
     */
//    public void createProcess(WorkTicketFlowDto workTicketFlowDto, LoginUser loginUserInfo) {
//        //流程步骤
//        ProcessStepDefinitionCreator stepBuilder = processService.processDefinitionExecutor().createProcessStep();
//        //创建流程节点
//        ProcessNodeDefinitionCreator nodeBuilder = processService.processDefinitionExecutor().createProcessNode();
//        WorkTicketPo workTicketPo = workTicketMapper.selectById(workTicketFlowDto.getWorkTicketId());
//        //工作票名字
//        String ticketName = workTicketPo.getTicketName();
//        //工作票发起人loginUserInfo.getLoginId()
//        Long userId = loginUserInfo.getUserId();
//        String username = loginUserInfo.getUsername();
//        //创建流程
//        ProcessDefinitionCreator creator = processService.processDefinitionExecutor().createProcess()
//                //工作流模板名称使用工作票ID+Name
//                //工作流模板内容使用工作票Name
//                //模板创建人使用登录人ID+Name
//                .processName(ticketName + workTicketFlowDto.getWorkTicketId()).processContent(ticketName).creator(userId + "," + username);
//        //设置流程步骤
//        List<WorkTicketDto> procedureList = workTicketFlowDto.getProcedureList();
//        ////                设置流程步骤            //流程节点定义信息
////                .step(stepBuilder.addNode(nodeBuilder.name("工作负责人").user("王二").build()).single()) //王二
////                .step(stepBuilder.addNode(nodeBuilder.name("工作票签发人").user("王三").build()).single())
////                .step(stepBuilder.addNode(nodeBuilder.name("值班负责人").user("王四").build()).single())
////                .step(stepBuilder.addNode(nodeBuilder.name("主管科长").user("王五").build()).single())
////                .step(stepBuilder.addNode(nodeBuilder.name("总工程师").user("王六").build()).single())
//
//        //添加默认发起节点 ，当流程开启时 需要默认通过（预防第一条审批无法驳回，需要添加一条无用审批）
//        creator.step(stepBuilder.addNode(nodeBuilder.name("发起流程").build()).single());
//        for (WorkTicketDto workTicketDto : procedureList) {
//            //节点名称使用职位ID和Name,审批人采用用户ID和name
//            creator.step(stepBuilder.addNode(nodeBuilder.name(workTicketDto.getPositionId() + "," + workTicketDto.getPositionName())
//                    .user(workTicketDto.getApproverId() + "," + workTicketDto.getApproverName()).build()).single());
//        }
//        //构造流程
//        ProcessParam processParam = creator.build();
//
//        //流程部署
//        DeployResult deployResult = processService.processExecutor()
//                .createProcessByData()
//                .workFlowRequest(processParam)
//                .deploy();
//        System.out.println(JSONUtil.toJsonPrettyStr(deployResult));
//
//    }


    /**
     * 工作票审批流程设置*
     *
     * @param workTicketFlowDto
     * @return
     */
    @Override
    public Boolean addApproveUpdate(WorkTicketFlowDto workTicketFlowDto) {
        //工作票ID
        String workTicketId = workTicketFlowDto.getWorkTicketId();
        WorkTicketPo workTicketPo = workTicketMapper.selectById(workTicketId);
        if (workTicketPo == null) {
            throw new HuaNengException(Constants.FAIL, "工作票ID不存在");
        }
        workTicketPo.setStepState("1");
        workTicketMapper.updateById(workTicketPo);
        //类型ID
        String ticketTypeId = workTicketPo.getTicketTypeId();
        //类型名称
        String ticketTypeName = workTicketPo.getTicketTypeName();

        // 步骤列表
        List<WorkTicketDto> procedureList = workTicketFlowDto.getProcedureList();
        int count = 0;
        for (WorkTicketDto workTicketDto : procedureList) {
            //流程
            WorkTicketFlowPo workTicketFlowPo = new WorkTicketFlowPo();
            workTicketFlowPo.setWorkTicketId(workTicketId);
            //工作票分类ID
            workTicketFlowPo.setTicketTypeId(ticketTypeId);
            //工作票分类名称
            workTicketFlowPo.setTicketTypeName(ticketTypeName);
            //序号列表
            workTicketFlowPo.setSerialNumbers(workTicketDto.getSerialNumbers());
            //职位ID
            workTicketFlowPo.setPositionId(workTicketDto.getPositionId());
            //职位名称
            workTicketFlowPo.setPositionName(workTicketDto.getPositionName());
            //发起人ID
            //发起人名称
            //JSON表单
            workTicketFlowPo.setJsonFrom(workTicketDto.getJsonFrom());
            //审批人ID
            workTicketFlowPo.setApproverId(workTicketDto.getApproverId());
            //审批人名称
            workTicketFlowPo.setApproverName(workTicketDto.getApproverName());
            count += workTicketFlowMapper.insert(workTicketFlowPo);
        }
        //创建工作流流程模板
        //禁用activiti
//        this.createProcess(workTicketFlowDto, getLoginUserInfo());

        if (procedureList.size() == count) {
            return true;
        }
        return false;
    }

    @Override
    public WorkTicketFlowDto approveById(String id) {
        WorkTicketPo workTicketPo = workTicketMapper.selectById(id);
        if (workTicketPo == null) {
            throw new HuaNengException(Constants.FAIL, "工作票ID不存在");
        }
        LambdaQueryWrapper<WorkTicketFlowPo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WorkTicketFlowPo::getWorkTicketId, id);
        List<WorkTicketFlowPo> workTicketFlowPos = workTicketFlowMapper.selectList(wrapper);
        if (workTicketFlowPos.isEmpty()) {
            return new WorkTicketFlowDto();
        }
        //返回格式
        WorkTicketFlowDto workTicketFlowDto = new WorkTicketFlowDto();
        workTicketFlowDto.setWorkTicketId(id);
        List<WorkTicketDto> collect = workTicketFlowPos.stream().map(t -> {
            WorkTicketDto workTicketDto = new WorkTicketDto();
            //审批流程模板ID
            workTicketDto.setFlowSchemeId(t.getFlowSchemeId());
            workTicketDto.setApproverId(t.getApproverId());
            workTicketDto.setJsonFrom(t.getJsonFrom());
            workTicketDto.setPositionId(t.getPositionId());
            workTicketDto.setPositionName(t.getPositionName());
            workTicketDto.setApproverId(t.getApproverId());
            workTicketDto.setApproverName(t.getApproverName());
            workTicketDto.setSerialNumbers(t.getSerialNumbers());
            return workTicketDto;
        }).collect(Collectors.toList());
        workTicketFlowDto.setProcedureList(collect);
        return workTicketFlowDto;
    }

    /**
     * 工作流查询当前任务列表
     *
     * @param businessKey
     * @return
     */
//    @Override
//    public List<ProcessHistoryResult> taskByid(String businessKey) {
//        ProcessExecutor processExecutor = processService.processExecutor();
//        //查询流程运行历史
//        List<ProcessHistoryResult> historyResults = processExecutor.createProcessQuery().businessKey(businessKey).processHistoryTracking();
//        return historyResults;
//    }

    /**
     * 工作流--开启流程审批
     *
     * @param businessKey
     * @param name
     * @param user
     * @return
     */
//    @Override
//    public ProcessTaskResult startProcess(String businessKey, String name, String user) {
//        ProcessTaskResult taskResult = processService.processExecutor().startProcess()
//                //发起人
//                .processName(name).businessKey(businessKey).applyUser(user).start();
//        //默认完成第一条发起审批
//        this.executeProcessTask(businessKey, 1, "发起审批同意", user);
//
//        return taskResult;
//    }

    /**
     * 完成任务
     *
     * @param businessKey
     * @param approve
     * @return
     */
//    @Override
//    public ProcessTaskResult executeProcessTask(String businessKey, Integer approve, String content, String user) {
//        TaskExecutor taskExecutor = processService.taskExecutor();
//        //查询通过businessKey查询任务参数
//        ProcessTaskResult variables = taskExecutor.createTaskVariablesQuery().businessKey(businessKey).query();
//        System.out.println(JSONUtil.toJsonPrettyStr(variables));
//
//        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
//
//        //执行任务
//        for (int i = 0; i < variables.getTasks().size(); i++) {
//            ProcessTaskResult executeResult = taskExecutor.taskId(variables.getTasks().get(i).getTaskId())
//                    .variable("approve", approve).variable("comment", approve == 0 ? content : content).executor(user).execute();
//            System.out.println(JSONUtil.toJsonPrettyStr(executeResult));
//            System.out.println("1111111111111111111111111111111111");
////            executeResult.isFinished();
//        }
//        return variables;
//    }

//    @Override
//    public String base(String businessKey) {
//        //输出流程运行图像Base64数据
//        ProcessExecutor processExecutor = processService.processExecutor();
//        String base64 = processExecutor.createProcessQuery().businessKey(businessKey).processImageBase64();
//        return base64;
//    }

    /**
     * 获取我的审批列表
     *
     * @return
     */
    @Override
    public List<ApproveVo> myApprove(String mineCode) {
        //获取登录人信息
        LoginUser loginUserInfo = getLoginUserInfo();
        //获取登录ID
        Long userId = loginUserInfo.getUserId();
        //获取所有工作票Data
        LambdaQueryWrapper<WorkDataPo> workDataPoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        workDataPoLambdaQueryWrapper.eq(StringUtils.isNotBlank(mineCode), WorkDataPo::getMineCode, mineCode);
        List<WorkDataPo> workDataPos = workTicketDataMapper.selectList(workDataPoLambdaQueryWrapper);
        if (workDataPos.isEmpty()) {
            return new ArrayList<>();
        }
        List<ApproveVo> approveVoList = new ArrayList<>();
        for (WorkDataPo workDataPo : workDataPos) {
            //获取所有的工作票流程Data
            LambdaQueryWrapper<WorkFlowDataPo> wrapper = new LambdaQueryWrapper<WorkFlowDataPo>();
            wrapper.eq(WorkFlowDataPo::getTicketDataId, workDataPo.getTickDataId());
            wrapper.eq(WorkFlowDataPo::getFlowStatus, "1");
            wrapper.eq(StringUtils.isNotBlank(mineCode), WorkFlowDataPo::getMineCode, mineCode);
            WorkFlowDataPo workFlowDataPo = workTicketFlowDataMapper.selectOne(wrapper);
            if (workFlowDataPo != null) {
                //有记录
                //获取审批人ID
                String approverId = workFlowDataPo.getApproverId();
                //判断登录人和审批人是同一个
                if (approverId.equals(userId.toString())) {

                    //返回数据
                    ApproveVo approveVo = new ApproveVo();
                    //工作票ID
                    approveVo.setTicketId(workDataPo.getTickDataId());
                    //工作票名称
                    approveVo.setTicketName(workDataPo.getTickName());
                    //工作票数据名称
                    approveVo.setTickDataName(workDataPo.getTickDataName());
                    //工作票分类ID
                    approveVo.setTicketTypeId(workDataPo.getTicketTypeId());
                    //工作票分类名称
                    approveVo.setTicketTypeName(workDataPo.getTicketTypeName());
                    //发起人ID
                    approveVo.setInitiatorId(workDataPo.getInitiatorId());
                    //发起人名称
                    approveVo.setInitiatorName(workDataPo.getInitiatorName());
                    //发起日期
                    approveVo.setFlowTakeDate(workDataPo.getFlowTakeDate());
                    //步骤状态
                    approveVo.setFlowStatus(workFlowDataPo.getFlowNumber() + "/" + workTicketFlowDataMapper.selectCount(new LambdaQueryWrapper<WorkFlowDataPo>().eq(WorkFlowDataPo::getTicketDataId, workDataPo.getTickDataId())));

                    approveVoList.add(approveVo);
                }
            }

        }
        return approveVoList;

        //遍历所有的ticketData数据表，拿到ID值  限定条件为flow_status:0  流程未完成

        //获取ID值后调用工作流查询当前任务列表  如果result的值为"处理中"
        //   {
        //      "comment": "完成",
        //      "taskId": "10edf047-409f-11ed-9336-00ff1fa5b646",
        //      "processDefinitionId": "5945a961-408c-11ed-abcd-00ff1fa5b646",
        //      "parentTaskId": "",
        //      "duration": 7574,
        //      "startTime": "2022-09-30 09:05:44",
        //      "endTime": "2022-09-30 09:05:52",
        //      "activityName": "工作负责人",
        //      "executor": "33",
        //      "result": "已完成"
        //    },
        //    {
        //      "comment": "",
        //      "taskId": "1573c692-409f-11ed-9336-00ff1fa5b646",
        //      "processDefinitionId": "5945a961-408c-11ed-abcd-00ff1fa5b646",
        //      "parentTaskId": "",
        //      "duration": 0,
        //      "startTime": "2022-09-30 09:05:52",
        //      "activityName": "工作票签发人",
        //      "result": "处理中"
        //    }

    }

    /**
     * 完成审批
     *
     * @return
     */
    @Override
    public Boolean accomplishApprove(String businessKey, Boolean is, String approve, String content) {

        List<WorkFlowDataPo> workFlowDataPos = workTicketFlowDataMapper.selectList(new LambdaQueryWrapper<WorkFlowDataPo>().eq(WorkFlowDataPo::getTicketDataId, businessKey));
        if (workFlowDataPos.isEmpty()) {
            throw new HuaNengException(Constants.FAIL, "工作票ID不存在");
        }
        //升序排序
        List<WorkFlowDataPo> collect = workFlowDataPos.stream().sorted(Comparator.comparing(WorkFlowDataPo::getFlowNumber)).collect(Collectors.toList());

        for (int i = 0; i < collect.size(); i++) {
            //流程状态(0未完成，1，审批中，2已完成，3拒绝)
            String flowStatus = collect.get(i).getFlowStatus();
            //获取审批中的记录
            if ("1".equals(flowStatus)) {
                //获取当前记录的详细信息
                WorkFlowDataPo workFlowDataPo = collect.get(i);

                //获取审批人
                String approverId = workFlowDataPo.getApproverId();
                String approverName = workFlowDataPo.getApproverName();

                //is为True 需要登录人审批
                if (is) {
                    //获取登录人信息
                    LoginUser loginUserInfo = getLoginUserInfo();
                    if (!approverId.equals(loginUserInfo.getUserId().toString())) {
                        throw new HuaNengException(Constants.FAIL, "登录人与审批人不是同一人");
                    }
                }
                if ("0".equals(approve)) {
                    //拒绝任务
                    WorkDataPo workDataPo = workTicketDataMapper.selectById(businessKey);
                    //该工作票设置为已拒绝
                    workDataPo.setFlowStatus("2");
                    workTicketDataMapper.updateById(workDataPo);
                    //将该审批列表设置为拒绝
                    workFlowDataPo.setFlowStatus("3");
                    workTicketFlowDataMapper.updateById(workFlowDataPo);
                    return true;
                }

                //获取登录人
                //使用完成审批
//                ProcessTaskResult processTaskResult = this.executeProcessTask(businessKey, Integer.parseInt(approve), content, approverId);
                //设置为审批已完成
                workFlowDataPo.setFlowStatus("2");
                workTicketFlowDataMapper.updateById(workFlowDataPo);

                //判断此审批是否是最后一个
                //list 集合中
                if (i < collect.size() - 1) {
                    //将下一条审批设置为审批中
                    WorkFlowDataPo workFlowDataPoNext = collect.get(i + 1);
                    workFlowDataPoNext.setFlowStatus("1");
                    workTicketFlowDataMapper.updateById(workFlowDataPoNext);

                    List<String> toUser = new ArrayList();
                    //获取当前审批人，给审批人发送消息
                    if (workFlowDataPoNext.getApproverId() != null) {
                        toUser.add(workFlowDataPoNext.getApproverId());
                        WeChartBaseMessage msg = new WeChartBaseMessage();
                        String content1 = "有待您审批的流程——" + "" + ",请登陆系统后审批。";
                        msg.setContent(content1);
                        msg.setPassword("hn@2022");
                        msg.setToUsers(org.apache.commons.lang3.StringUtils.join(toUser, ","));
                        try {
                            remoteMineInfoService.sendBaseMessage(msg);
                        } catch (Exception e) {
                            System.out.println("发送审批消息失败，flowID，审批人" +workFlowDataPoNext.getFlowId()+","+ workFlowDataPoNext.getApproverId());
                            e.printStackTrace();
                        }

                    }


                } else {
                    //已经是最后一条记录
                    WorkDataPo workDataPo = workTicketDataMapper.selectById(businessKey);
                    workDataPo.setFlowStatus("1");
                    workTicketDataMapper.updateById(workDataPo);
                }
                return true;

            }
        }
        return false;
    }

    /**
     * 根据工作票DataID获取审批序号列表
     *
     * @param id
     * @return
     */
    @Override
    public WorkTicketFlowDataDto approveDataById(String id) {
        WorkDataPo workDataPo = workTicketDataMapper.selectById(id);
        if (workDataPo == null) {
            throw new HuaNengException(Constants.FAIL, "工作票ID不存在");
        }
        WorkTicketFlowDataDto workTicketFlowDataDto = new WorkTicketFlowDataDto();
        workTicketFlowDataDto.setFromData(workDataPo.getFromData());
        workTicketFlowDataDto.setWorkTicketId(workDataPo.getTickDataId());
        LambdaQueryWrapper<WorkFlowDataPo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WorkFlowDataPo::getTicketDataId, id);
        List<WorkFlowDataPo> workFlowDataPos = workTicketFlowDataMapper.selectList(wrapper);
        workTicketFlowDataDto.setProcedureList(workFlowDataPos);
        return workTicketFlowDataDto;
    }

    /**
     * From表单修改
     *
     * @param fromUpdateDto
     * @return
     */
    @Override
    public Boolean fromUpdate(FromUpdateDto fromUpdateDto) {
        WorkDataPo workDataPo = new WorkDataPo();
        workDataPo.setTickDataId(fromUpdateDto.getId());
        workDataPo.setFromData(fromUpdateDto.getFromData());
        int i = workTicketDataMapper.updateById(workDataPo);
        if (i > 0) {
            return true;
        }
        return false;
    }

    /**
     * 撤销审批
     *
     * @param id
     * @return
     */
    @Override
    public Boolean revocationApproveById(String id) {
        //登录ID
        LoginUser loginUserInfo = getLoginUserInfo();


        //工作票数据ID
        WorkDataPo workDataPo = workTicketDataMapper.selectById(id);
        if (workDataPo == null) {
            throw new HuaNengException(Constants.FAIL, "工作票数据ID不存在");
        }
        if (!loginUserInfo.getUserId().toString().equals(workDataPo.getInitiatorId())) {
            throw new HuaNengException(Constants.FAIL, "请使用发起人账号撤销审批");
        }

        LambdaQueryWrapper<WorkFlowDataPo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WorkFlowDataPo::getTicketDataId, id);
        List<WorkFlowDataPo> workFlowDataPos = workTicketFlowDataMapper.selectList(wrapper);
        if (workFlowDataPos.isEmpty()) {
            throw new HuaNengException(Constants.FAIL, "流程为空");
        }
        for (WorkFlowDataPo workFlowDataPo : workFlowDataPos) {
            //流程状态(0未完成，1，审批中，2已完成，3拒绝,4已撤销
            if ("1".equals(workFlowDataPo.getFlowStatus())) {
                workFlowDataPo.setFlowStatus("4");
                workTicketFlowDataMapper.updateById(workFlowDataPo);
            }
            break;
        }
        //流程状态(0未完成,1已完成，2已拒绝，3已撤销
        workDataPo.setFlowStatus("3");
        workTicketDataMapper.updateById(workDataPo);
        try {
//            revocation(id);
        } catch (HuaNengException e) {
            return false;
        }
        return true;
    }

    /**
     * 工作流--撤销审批
     *
     * @param businessKey
     * @return
     */
//    @Override
//    public void revocation(String businessKey) {
//        processService.processExecutor().businessKey(businessKey).endProcess();
//
//    }

    /**
     * 删除审批
     *
     * @param businessKey
     */
//    @Override
//    public void delete(String businessKey) {
//        processService.processExecutor().businessKey(businessKey).deleteProcess();
//    }

    /**
     * 暂停运行的流程实例
     *
     * @param businessKey
     */
//    @Override
//    public void suspend(String businessKey) {
//        processService.processExecutor().businessKey(businessKey).suspendProcess();
//    }

    /**
     * 激活暂停的流程实例
     *
     * @param businessKey
     */
//    @Override
//    public void activate(String businessKey) {
//        processService.processExecutor().businessKey(businessKey).activateProcess();
//    }

    /**
     * 审批批量删除
     *
     * @param idList
     * @return
     */
    @Override
    public Boolean approveDelete(List<String> idList) {
        int count = 0;
        for (String s : idList) {
            int i = workTicketDataMapper.deleteById(s);
            if (i == 0) {
                throw new HuaNengException(Constants.FAIL, "此ID删除失败" + s);
            }
            count += i;
            workTicketFlowDataMapper.delete(new LambdaQueryWrapper<WorkFlowDataPo>().eq(WorkFlowDataPo::getTicketDataId, s));

            try {
                //删除工作流
                //禁用activiti
//                this.delete(s);
            } catch (HuaNengException e) {
                System.out.println("工作流删除出错");

            }
        }
        if (count == idList.size()) {
            return true;
        }
        return false;
    }

    /**
     * 审批人员-新增审批人员
     * @param idList
     * @return
     */
    @Override
    public Boolean personAdd(List<Long> idList,String mineCode) {
        for (Long aLong : idList) {
            if (workPersonMapper.selectList(new LambdaQueryWrapper<WorkPersonPo>().eq(WorkPersonPo::getUserId, aLong).eq(StringUtils.isNotBlank(mineCode), WorkPersonPo::getMineCode, mineCode)).isEmpty()) {
                WorkPersonPo workPersonPo = new WorkPersonPo();
                workPersonPo.setUserId(aLong);
                if (StringUtils.isNotBlank(mineCode)) {
                    workPersonPo.setMineCode(mineCode);
                }
                workPersonMapper.insert(workPersonPo);
            }
        }
        return true;
    }

    /**
     * 审批人员-批量删除审批人员
     * @param idList
     * @return
     */
    @Override
    public Boolean personDelete(List<Long> idList,String mineCode) {
        int sum = 0;
        for (Long aLong : idList) {
            LambdaQueryWrapper<WorkPersonPo> lambdaQueryWrapper = new LambdaQueryWrapper<WorkPersonPo>()
                    .eq(WorkPersonPo::getUserId, aLong)
                    .eq(StringUtils.isNotBlank(mineCode), WorkPersonPo::getMineCode, mineCode);
            sum += workPersonMapper.delete(lambdaQueryWrapper);
        }
        if (sum == idList.size()) {
            return true;
        }
        return false;
    }

    /**
     * 审批人员-已添加审批人员列表
     * @return
     */
    @Override
    public List<UserVo> personTrueApprovalList(String mineCode) {
        //查询条件添加煤矿编码
        LambdaQueryWrapper<WorkPersonPo> lambdaQueryWrapper = new LambdaQueryWrapper<WorkPersonPo>().eq(StringUtils.isNotBlank(mineCode), WorkPersonPo::getMineCode, mineCode);
        //获取所有可审批人员
        List<WorkPersonPo> workPersonPos = workPersonMapper.selectList(lambdaQueryWrapper);
        if (workPersonPos.isEmpty()) {
            return new ArrayList<>();
        }
        //人员签名集合
        Map<Long, String> personMap = workPersonPos.stream().collect(Collectors.toMap(WorkPersonPo::getUserId, p -> Optional.ofNullable(p.getSignaturePicture()).orElse("")));

        List<Long> collect = workPersonPos.stream().map(t->{return t.getUserId();}).collect(Collectors.toList());
        //远程调用
        List<UserVo> userListIds = remoteUserService.getUserListIds(collect);

        //遍历人员集合设置签名
        userListIds.forEach(userVo -> {
            userVo.setSignaturePicture(personMap.get(userVo.getUserId()));
        });
        return userListIds;
    }

    /**
     * 审批人员-未添加审批人员列表
     * @return
     */
    @Override
    public List<UserVo> personFalseApprovalList(String mineCode) {
        //查询条件添加煤矿编码
        LambdaQueryWrapper<WorkPersonPo> lambdaQueryWrapper = new LambdaQueryWrapper<WorkPersonPo>().eq(StringUtils.isNotBlank(mineCode), WorkPersonPo::getMineCode, mineCode);
        //获取所有用户id
        List<WorkPersonPo> workPersonPos = workPersonMapper.selectList(lambdaQueryWrapper);
        if (workPersonPos.isEmpty()) {
            //获取所有的用户
            return remoteUserService.getUserAllList();
        }
        List<Long> collect = workPersonPos.stream().map(t -> {
            return t.getUserId();
        }).collect(Collectors.toList());
        //远程调用排除ids
        List<UserVo> userListExcludeIds = remoteUserService.getUserListExcludeIds(collect);
        return userListExcludeIds;
    }

    /**
     * 审批人员-根据用户id设置审批图片
     * @param userId
     * @param mineCode
     * @param url
     * @return
     */
    @Override
    public Boolean personSetSignaturePicture(Long userId, String mineCode, String url) {
        //查询当前用户是否在审批表中
        WorkPersonPo workPersonPo = workPersonMapper.selectOne(new LambdaQueryWrapper<WorkPersonPo>()
                .eq(WorkPersonPo::getUserId, userId)
//                .eq(WorkPersonPo::getDelFlag, "0")
                .eq(StringUtils.isNotBlank(mineCode), WorkPersonPo::getMineCode, mineCode));
        if (workPersonPo == null) {
            throw new HuaNengException(Constants.FAIL, "当前更新用户未在审批表中，请在审批表中添加当前用户："+userId);
        }
        workPersonPo.setSignaturePicture(url);
        int i = workPersonMapper.updateById(workPersonPo);
        if (i > 0) {
            return true;
        }
        return false;
    }

    @Override
    public String getSignaturePicture(Long userId, String mineCode) {
        if (userId == null) {
            //获取登录人信息
            LoginUser loginUserInfo = getLoginUserInfo();
            //获取登录ID
            userId = loginUserInfo.getUserId();
        }
        WorkPersonPo workPersonPo = workPersonMapper.selectOne(new LambdaQueryWrapper<WorkPersonPo>()
                .eq(WorkPersonPo::getUserId, userId)
//                .eq(WorkPersonPo::getDelFlag, "0")
                .eq(StringUtils.isNotBlank(mineCode), WorkPersonPo::getMineCode, mineCode));
        if (workPersonPo == null) {
            throw new HuaNengException(Constants.FAIL, "未查询到当前用户："+userId);
        }
        //判断url 是否为空
        String signaturePicture = workPersonPo.getSignaturePicture();
        if (StringUtils.isEmpty(signaturePicture)) {
            return "";
        }
        return signaturePicture;
    }


    /**
     * 获取登录用户详细
     */
    private LoginUser getLoginUserInfo() {
        LoginUser loginUser;
        try {
            loginUser = LoginHelper.getLoginUser();
        } catch (Exception e) {
            throw new HuaNengException(Constants.FAIL, "用户未登录,查询不到登录用户信息,无法录入发起人");
        }
        return loginUser;
    }


}
